package com.sjs.boot.dynamic.facade.run;

import cn.hutool.core.util.StrUtil;
import com.sjs.boot.dynamic.util.ValParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author uto_dev_008
 * @desc
 * @since 2021/11/9 19:26
 */
public abstract class AbstractHandler {
    private static final Logger LOG = LoggerFactory.getLogger(AbstractHandler.class);

    private static final String CONFIG_PROCESSOR = "processor";


    /**
     * 初始化
     * @return
     */
    abstract public boolean init();

    /**
     * 销毁
     */
    abstract public void destroy();

    public static AbstractHandler getHandler(Map<String, Object> json, AbstractHandler defaultHandler) {
        String clsName = ValParser.getAsStr(json, CONFIG_PROCESSOR, null);
        if(StrUtil.isEmpty(clsName)) {
            return defaultHandler;
        }

        try {
            @SuppressWarnings("unchecked")
            Class<? extends AbstractHandler> cls = (Class<? extends AbstractHandler>)Class.forName(clsName);
            if(!defaultHandler.getClass().isAssignableFrom(cls)) {
                LOG.error("{} is not sub-class of {}", cls.getName(), defaultHandler.getClass().getName());
                return null;
            }

            AbstractHandler handler = (AbstractHandler)cls.newInstance();
            if(!handler.init()) {
                LOG.error("Fail to call {}.init()", clsName);
                return null;
            }
            return handler;
        } catch(Exception e) {
            LOG.error("Fail to load processor {}", clsName, e);
            return null;
        }
    }
}
